package com.work.web.filter;

import com.work.web.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthService authService;

    public static final String login_url = "http://localhost:8001/api/oauth/login";


    /*1）判断当前请求是否为登录请求，是的话，则放行

2) 判断cookie中是否存在信息, 没有的话，拒绝访问

3）判断redis中令牌是否存在，没有的话，拒绝访问*/

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        if (path.contains("/api/oauth/login")||!UrlFilter.hasAuthorize(path)) {
            //如果包含了登录了路径,则放行
            return chain.filter(exchange);
        }

        //判断cookie中是否存在信息, 没有的话，拒绝访问
        String jti = authService.getJtiFromCookie(request);
        if(StringUtils.isEmpty(jti)){
            //跳转到登录页面
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().set("Location",login_url+"?from="+path);
            return  response.setComplete();
        }

        //判断redis中令牌是否存在，没有的话，拒绝访问
        String token = authService.getTokenFromRedis(jti);
        if(StringUtils.isEmpty(token)){
            //跳转到登录页面
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().set("Location",login_url+"?from="+path);
            return response.setComplete();
        }

        //校验通过，请求头增强，放行
        request.mutate().header("Authorization","Bearer "+token);

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
